<?php
require_once("lib.php");
header('Content-Type: application/json');
if (!isset($_POST["t"])) {
    echo json_encode(array("status" => "error", "message" => "missing post parameter"));
    exit;
}

$trackID = $_POST["t"];
$meters = true;
if (isset($_POST["m"]) && ($_POST["m"] == "f")) {
    $meters = false;
}

$trackTable = null;
$trackName = null;
$stmt = $db->prepare("SELECT tableName, trackName FROM track_tables_info WHERE ID = :trackID");
if ($stmt->execute(array("trackID" => $trackID))) {
    $row = $stmt->fetch(PDO::FETCH_ASSOC);
    $trackTable = $row["tableName"];
    $trackName = $row["trackName"];
} else {
    echo json_encode(array("status" => "error", "message" => "failed to query track table name"));
    exit;
}
$stmt = $db->prepare("SELECT time, ele FROM $trackTable ORDER BY time");
if ($stmt->execute()) {
    $rows = Array();
    while ($row = $stmt->fetch()) {
        if (!$meters) {
            $ele = Util::meters2feet($row["ele"]);
        } else {
            $ele = $row["ele"];
        }
        $timeParts = explode(" ", $row["time"]);
        $rows[] = array("c" => array(array("v" => $timeParts[1]), array("v" => $ele)));
    } 
    $cols[] = array("label" => "time", "type" => "string");
    $cols[] = array("label" => "meters",   "type" => "number");

    echo json_encode(array("cols" => $cols, "rows" => $rows));
} else {
    echo json_encode(array("status" => "error", "message" => "failed to query track data (" . $stmt->debugDumpParams() . ")"));
    exit;
}

?>
